package com.apexwear.apexutils.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.apexwear.apexutils.R;
import com.apexwear.apexutils.adapter.AdapterDeviceList;
import com.apexwear.apexutils.api.OnItemClickListener;
import com.apexwear.apexutils.common.Constant;
import com.apexwear.apexutils.databinding.ActivityScanBinding;
import com.apexwear.apexutils.model.Device;
import com.apexwear.apexutils.scan.BluetoothScanUtils;
import com.apexwear.apexutils.utils.PermissionUtils;
import com.apexwear.apexutils.utils.ShowToast;
import com.cazaea.sweetalert.SweetAlertDialog;

import java.util.ArrayList;
import java.util.List;

public class AddHeartBlueDeviceActivity extends AppCompatActivity {
    private ActivityScanBinding dataBinding;
    private AdapterDeviceList adapterDeviceList;
    private List<Device> deviceList;
    BluetoothScanUtils bluetoothScanUtils;
    private volatile boolean isDestroy;
    private int currentPosition;
    SweetAlertDialog sweetAlertDialog;
    FinishBroadcast finishBroadcast;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x05 && !isDestroy) {
                if (bluetoothScanUtils == null) {
                    bluetoothScanUtils = BluetoothScanUtils.getBluetoothScanInstance();
                }
                List<Device> dList = bluetoothScanUtils.getDeviceList();
                if (dList != null && dList.size() > currentPosition) {
                    List<Device> tempList = new ArrayList<>();
                    for (int i = currentPosition; i < dList.size(); i++) {
                        tempList.add(dList.get(i));
                    }
                    if (tempList != null && !tempList.isEmpty()) {
                        if (deviceList != null) {
                            deviceList.addAll(tempList);
                        }
                        if (adapterDeviceList != null) {
                            adapterDeviceList.notifyItemRangeChanged(currentPosition, dList.size());
                        }
                    }
                    currentPosition = deviceList.size();

                }
                if (mHandler != null && !isDestroy) {
                    mHandler.sendEmptyMessageDelayed(0x05, 1000);
                }
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_scan);
        dataBinding.tooBar.setNavigationIcon(R.mipmap.exit_page);
        setSupportActionBar(dataBinding.tooBar);
        getSupportActionBar().setTitle(null);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        deviceList = new ArrayList<>();
        adapterDeviceList = new AdapterDeviceList(this, deviceList);
        dataBinding.deviceList.setLayoutManager(linearLayoutManager);
        dataBinding.deviceList.setAdapter(adapterDeviceList);
        dataBinding.tooBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        if (finishBroadcast == null) {
            finishBroadcast = new FinishBroadcast();
            LocalBroadcastManager.getInstance(this).registerReceiver(finishBroadcast,new IntentFilter(Constant.CONNECT_HEART_DEVICE_STATE_BROADCAST));

        }
        adapterDeviceList.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void clickListener(int position) {
                isDestroy = true;
                if (sweetAlertDialog == null) {
                    sweetAlertDialog = new SweetAlertDialog(AddHeartBlueDeviceActivity.this, SweetAlertDialog.PROGRESS_TYPE);
                    sweetAlertDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
                    sweetAlertDialog.setTitleText(getString(R.string.Binding));
                    sweetAlertDialog.setCancelable(false);
                    sweetAlertDialog.setCancelable(false);
                    sweetAlertDialog.setCanceledOnTouchOutside(false);
                }
                if (!sweetAlertDialog.isShowing()) {
                    sweetAlertDialog.show();
                }
                if (mHandler != null) {
                    mHandler.removeCallbacksAndMessages(null);
                }
                if (bluetoothScanUtils != null) {
                    bluetoothScanUtils.stopScan();
                }

                Intent intent = new Intent(Constant.CONNECT_HEART_DEVICE_BROADCAST);
                intent.putExtra("watch_info", deviceList.get(position));
                LocalBroadcastManager.getInstance(AddHeartBlueDeviceActivity.this).sendBroadcast(intent);
            }
        });
        if (PermissionUtils.checkLocationPermission(AddHeartBlueDeviceActivity.this)) {
            if (bluetoothScanUtils == null) {
                bluetoothScanUtils = BluetoothScanUtils.getBluetoothScanInstance();
            }
            if (!bluetoothScanUtils.isScanning()) {
                bluetoothScanUtils.startEABleBluetoothScan();
            }
            if (mHandler != null) {
                mHandler.sendEmptyMessageDelayed(0x05, 300);
            }

        } else {
            PermissionUtils.requestLocationPermission(AddHeartBlueDeviceActivity.this);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0x03) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (bluetoothScanUtils == null) {
                    bluetoothScanUtils = BluetoothScanUtils.getBluetoothScanInstance();
                }
                if (!bluetoothScanUtils.isScanning()) {
                    bluetoothScanUtils.startEABleBluetoothScan();
                }
                if (mHandler != null) {
                    mHandler.sendEmptyMessageDelayed(0x05, 300);
                }

            } else {
                ShowToast.show(AddHeartBlueDeviceActivity.this, getString(R.string.open_scan_permission));
            }
        } else if (requestCode == 0x04) {
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                ShowToast.show(AddHeartBlueDeviceActivity.this, getString(R.string.open_connect_permission));
            }
        } else if (requestCode == 0x02) {
            boolean isPermission = true;
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    isPermission = false;
                    break;
                }
            }
            if (!isPermission) {
                ShowToast.show(AddHeartBlueDeviceActivity.this, getString(R.string.location_permission));
            } else {
                if (bluetoothScanUtils == null) {
                    bluetoothScanUtils = BluetoothScanUtils.getBluetoothScanInstance();
                }
                if (!bluetoothScanUtils.isScanning()) {
                    bluetoothScanUtils.startEABleBluetoothScan();
                }
                if (mHandler != null) {
                    mHandler.sendEmptyMessageDelayed(0x05, 300);
                }

            }
        }
    }

    @Override
    public void onBackPressed() {
        isDestroy = true;
        super.onBackPressed();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (bluetoothScanUtils != null) {
            bluetoothScanUtils.stopScan();
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    protected void onDestroy() {
        isDestroy = true;
        if (finishBroadcast != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(finishBroadcast);
            finishBroadcast = null;
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        if (sweetAlertDialog != null) {
            sweetAlertDialog.dismiss();
            sweetAlertDialog = null;
        }
        dataBinding.deviceList.setLayoutManager(null);
        dataBinding.deviceList.setAdapter(null);
        dataBinding.deviceList.clearAnimation();
        dataBinding.deviceList.removeAllViews();
        if (adapterDeviceList != null) {
            adapterDeviceList.destroyAdapter();
            adapterDeviceList = null;
        }
        deviceList = null;
        if (dataBinding != null) {
            dataBinding.unbind();
            dataBinding = null;
        }
        bluetoothScanUtils = null;
        super.onDestroy();
    }

    class FinishBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (!TextUtils.isEmpty(action)) {
                if (action.equalsIgnoreCase(Constant.CONNECT_HEART_DEVICE_STATE_BROADCAST)) {
                    if (sweetAlertDialog != null) {
                        sweetAlertDialog.dismiss();
                    }
                    boolean state = intent.getBooleanExtra("connect_state", false);
                    if (state) {
                        isDestroy = true;
                        finish();
                    } else {
                        ShowToast.show(AddHeartBlueDeviceActivity.this, getString(R.string.failed_to_bind_the_watch));
                    }
                }
            }
        }
    }
}
